package xrocketmq

import (
	"context"
	"errors"
	"fmt"
	"github.com/apache/rocketmq-client-go/v2"
	"github.com/apache/rocketmq-client-go/v2/primitive"
	"github.com/apache/rocketmq-client-go/v2/producer"
)

func NewProducer(groupName, topic string, str string, delay int, address []string) error {
	res, err := rocketmq.NewProducer(
		producer.WithGroupName(groupName),
		producer.WithNsResolver(primitive.NewPassthroughResolver(address)),
		producer.WithRetry(2),
	)
	if err != nil {
		return err
	}

	err = res.Start()
	if err != nil {
		return err
	}

	msg := &primitive.Message{
		Topic: topic,
		Body:  []byte(str),
	}
	msg.WithDelayTimeLevel(delay)
	// 发送
	_, err = res.SendSync(context.Background(), msg)
	if err != nil {
		return errors.New(fmt.Sprintf("发送消息失败 : %s\n", err))
	}

	err = res.Shutdown()
	if err != nil {
		return errors.New(fmt.Sprintf("producer shutdown errpr : %s\n", err))
	}
	return nil
}
